<?php
class smonitor{
	function check($url,$id){
		$pos=stripos($url,".m3u8");
		$pos554=stripos($url,":554");
		if($pos>0){
			return $this->checkm3u8($url,$id);
		}
		else{
			if($pos554>0)
				return $this->check554($url);
			else
				return $this->checkfile($url);
		}
	}
	function checkfile($url){
		$url=str_replace("xttp:","http:",$url);
		system("wget --spider --timeout=4 --tries=2 -q '$url'",$result);
		return $result;
	}
	function check554($url){//soooner 554 不支持--spider参数，只检查端口是否可用
		preg_match("#http:\/\/(.*?):([\d]*?)\/#i",$url,$m1);	
		$ip=$m1[1];
		$port=$m1[2];
		$fp = fsockopen($ip, $port, $errno, $errstr, 8);
		if($fp){
			fclose($ps);
			return 0;
		}
		return 1;
	}
	function checkm3u8($url,$id){
		$r=$this->checkfile($url);
		if($r!="0")
			return 1;
		preg_match("#http:\/\/.*?\/#i",$url,$m1);
		preg_match("#http:\/\/.*\/#i",$url,$m2);
		$siteroot=$m1[0];
		$siteroot=substr($siteroot, 0, -1);  
		$sitecurrent=$m2[0];
		$text=file_get_contents($url);
		$newv=md5($text);
        $oldv=file_get_contents("/tmp/check_v_$id");
        file_put_contents("/tmp/check_v_$id",$newv);
        if($newv==$oldv)
            return 1;
		preg_match_all('/^[^#\s]*$/mi', $text, $match);
		foreach($match[0] as $c){
			$c=trim($c);
			if($c){
				if($c[0]=="/"){
					$c=substr($c,1);
					$newurl=$siteroot.$c;
				}else{
					$newurl=$sitecurrent.$c;
				}
				//echo $newurl."\n";
				$r=$this->checkfile($newurl);
				if($r!="0")
					return 1;
			}
		}
		return 0;
	}
}
